package com.ainiyar.springweb.service.impl;

import com.ainiyar.springweb.common.result.ResultResponse;
import com.ainiyar.springweb.mapper.RoleMapper;
import com.ainiyar.springweb.mapper.RolePermissionMapper;
import com.ainiyar.springweb.pojo.admin.dto.PageDto;
import com.ainiyar.springweb.pojo.admin.vo.RoleVo;
import com.ainiyar.springweb.pojo.admin.vo.SelectVo;
import com.ainiyar.springweb.pojo.entity.Role;
import com.ainiyar.springweb.pojo.entity.RolePermission;
import com.ainiyar.springweb.service.MenuService;
import com.ainiyar.springweb.service.RoleService;
import com.ainiyar.springweb.util.ToolsUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.If;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.List;

import static com.ainiyar.springweb.pojo.entity.table.RoleTableDef.ROLE;
import static com.ainiyar.springweb.pojo.entity.table.RolePermissionTableDef.ROLE_PERMISSION;

/**************************************
 * File Name : RoleServiceImpl
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/5  01:01
 * Desc :
 ***************************************/
@Service
@Transactional
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Resource
    private MenuService menuService;

    /**
     * 角色列表
     *
     * @param page   分页参数
     * @param name   查询条件 角色名称
     * @param status 查询条件 角色状态
     * @return 列表数据
     */
    @Override
    public ResultResponse<Object> lists(PageDto page, String name, Integer status) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ROLE.DEFAULT_COLUMNS)
                .where(ROLE.NAME.like(name, If::hasText))
                .and(ROLE.STATUS.eq(status, If::notNull))
                .orderBy(ROLE.ID.desc());
        Page<Role> rolePage = Page.of(page.getPage(), page.getPageSize());
        rolePage = roleMapper.paginate(rolePage, queryWrapper);
        List<RoleVo> roleList = new ArrayList<>();
        for (Role record : rolePage.getRecords()) {
            RoleVo role = new RoleVo();
            BeanUtils.copyProperties(record,role);
            String status_text = record.getStatus() == 1 ? "启用" : "停用";
            role.setStatusText(status_text);
            role.setCreateTime(ToolsUtil.LocalDateTimeFormat(record.getCreateTime()));
            if (record.getUpdateTime() != null) {
                role.setUpdateTime(ToolsUtil.LocalDateTimeFormat(record.getUpdateTime()));
            }
            Object[] permissionIds = getPermissionByRoleId(record.getId()).toArray(new Object[0]);
            role.setPermission(List.of(permissionIds));
            role.setPermissionList(menuService.getMenuForRoleByIds(permissionIds));
            roleList.add(role);
        }
        return ResultResponse.pageList(roleList, rolePage.getPageNumber(), rolePage.getPageSize(), rolePage.getTotalRow(), rolePage.getTotalPage());
    }

    /**
     * 保存新增，修改角色数据
     *
     * @param role 角色数据
     * @return true:成功  false:失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAddEdit(Role role) {
        try {
            Role roleEntity = new Role();
            if (role.getId() != null && role.getId() != 0) {
                roleEntity.setId(role.getId());
            }
            roleEntity.setName(role.getName());
            roleEntity.setRoleDescribe(role.getRoleDescribe());
            roleEntity.setStatus(role.getStatus());
            if (roleMapper.insertOrUpdateSelective(roleEntity) == 0) {
                return false;
            }
            //处理角色权限
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .where(ROLE_PERMISSION.ROLE_ID.eq(roleEntity.getId()));
            rolePermissionMapper.deleteByQuery(queryWrapper);
            //批量添加角色权限
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (long record : role.getPermissionList()) {
                RolePermission permission = new RolePermission();
                permission.setRoleId(roleEntity.getId());
                permission.setPermissionId(record);
                rolePermissions.add(permission);
            }
            if (rolePermissionMapper.insertBatch(rolePermissions) == 0) {
                return false;
            }
            ;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    /**
     * 删除角色
     *
     * @param id 所需删除角色id
     * @return true:成功  false:失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id) {
        try {
            if (roleMapper.deleteById(id) == 0) {
                return false;
            }
            QueryWrapper queryWrapper = QueryWrapper.create()
                    .where(ROLE_PERMISSION.ROLE_ID.eq(id));
            if (rolePermissionMapper.deleteByQuery(queryWrapper) == 0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    /**
     * 为下拉框
     */
    @Override
    public List<SelectVo> getRoleForSelect() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ROLE.ID, ROLE.NAME)
                .from(ROLE)
                .orderBy(ROLE.ID.asc());
        List<Role> list = roleMapper.selectListByQuery(queryWrapper);
        List<SelectVo> selectValueList = new ArrayList<>();
        for (Role record : list) {
            SelectVo selectValue = new SelectVo();
            selectValue.setKey(record.getId());
            selectValue.setLabel(record.getName());
            selectValueList.add(selectValue);
        }
        return selectValueList;
    }

    /**
     * 根据管理角色id获取角色信息
     * @param role_id 角色id
     * @return 角色信息
     */
    @Override
    public Role getRoleByAdminRoleId(Long role_id) {
        return roleMapper.selectOneById(role_id);
    }

    private List<Object> getPermissionByRoleId(Long role_id) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(ROLE_PERMISSION.PERMISSION_ID)
                .from(ROLE_PERMISSION)
                .where(ROLE_PERMISSION.ROLE_ID.eq(role_id));
        return rolePermissionMapper.selectObjectListByQuery(queryWrapper);
    }
}

